package top.hidoctor.auscultation.feature.activity;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.tang.user.UserInfoManager;
import com.tang.util.GsonUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.RenyuanAdapter;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.bean.LabelUser;
import top.hidoctor.auscultation.bean.Sample;
import top.hidoctor.auscultation.bean.UserBean;
import top.hidoctor.auscultation.bean.YangbenBean;
import top.hidoctor.auscultation.event.AddAuditSDEvent;
import top.hidoctor.auscultation.event.AddLabelSDEvent;
import top.hidoctor.auscultation.net.c.ExampleChooseContract;
import top.hidoctor.auscultation.net.c.LabelSdReq;
import top.hidoctor.auscultation.net.req.UserReq;
import top.hidoctor.auscultation.net.p.ExampleChoosePresenter;
import top.hidoctor.auscultation.net.req.AuditSdReq;

public class RenyuanListActivity extends BaseActivity implements ExampleChooseContract.View {
    private RecyclerView recycler;
    private Button btnFinish;
    private ExampleChoosePresenter presenter;
    private UserReq req;
    private SwipeRefreshLayout refreshLayout;
    private RenyuanAdapter adapter;
    private EditText editSearch;
    private LabelSdReq labelSdReq;
    private String type;
    private AuditSdReq auditSdReq;
    private String userId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_renyuan_list);

        type = getIntent().getStringExtra("type");
        presenter = new ExampleChoosePresenter(this, this);
        req = new UserReq();
        if (type.equals("1")) {
            req.setRoleIds("[\"3124297098854400\"]");
        } else {
            req.setRoleIds("[\"3124297241460736\"]");
        }
        labelSdReq = new LabelSdReq();
        auditSdReq = new AuditSdReq();
        req.setIsDeleted(1);
        req.setStatus("2");
        req.setScope(2);
        initView();
        initEvent();
    }


    private void initView() {
        final Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoft(toolbar);
                onBackPressed();
            }
        });
        refreshLayout = findViewById(R.id.refreshLayout);
        recycler = findViewById(R.id.recycler);
        editSearch = findViewById(R.id.edit_search);
        btnFinish = findViewById(R.id.btn_finish);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter = new RenyuanAdapter(R.layout.item_renyuan, null));
        recycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        View view = LayoutInflater.from(this).inflate(R.layout.layout_empty_list, (ViewGroup) recycler.getParent(), false);
        adapter.setEmptyView(view);
        adapter.isFirstOnly(false);
        adapter.openLoadAnimation();
        adapter.openLoadMore(10, true);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });

        adapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (type.equals("1")) {
                    adapter.getData().get(position).setCheck(!adapter.getData().get(position).isCheck());
                    adapter.notifyItemChanged(position);
                } else {
                    for (int i = 0; i < adapter.getData().size(); i++) {
                        adapter.getData().get(i).setCheck(false);
                    }
                    userId = adapter.getData().get(position).getId();
                    adapter.getData().get(position).setCheck(true);
                    adapter.notifyDataSetChanged();
                }

            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                hideSoft(recycler);
                req.setKeyWord(editSearch.getText().toString().trim());
                refresh();
            }
        });
        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            req.setKeyWord(v.getText().toString().trim());
                            refresh();
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });

        refresh();
    }

    /**
     * 上垃加载
     */
    private void loadMore() {
        req.setPageNo(1 + req.getPageNo());
        presenter.getUserList(req, refreshLayout);
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        req.setPageNo(1);
        presenter.getUserList(req, refreshLayout);
    }


    private void initEvent() {
        final String info = getIntent().getStringExtra("info");
        final List<Sample> beans = GsonUtil.parseJson(info, new TypeToken<List<Sample>>() {
        });


        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<LabelUser> checkList = new ArrayList<>();
                for (int i = 0; i < adapter.getData().size(); i++) {
                    if (adapter.getData().get(i).isCheck()) {
                        checkList.add(new LabelUser(adapter.getData().get(i).getId()));
                    }
                }
                if (checkList.size() == 0) {
                    showToast("请选择人员");
                    return;
                }
                if (type.equals("1")) {
                    if (checkList.size() != 2) {
                        showToast("标注人员只能选择2个");
                        return;
                    }
                }
                if (type.equals("1")) {
                    labelSdReq.setSample(beans);
                    labelSdReq.setHospitalId(UserInfoManager.getInstance().getUserInfo().getHospitalId());
                    labelSdReq.setLabelUsers(checkList);
                    presenter.addLabel(labelSdReq);
                } else {
                    auditSdReq.setSample(beans);
                    auditSdReq.setHospitalId(UserInfoManager.getInstance().getUserInfo().getHospitalId());
                    auditSdReq.setType(20);
                    auditSdReq.setUserId(userId);
                    presenter.addLabel2(auditSdReq);
                }

            }
        });
    }

    @Override
    public void getYbListSuc(YangbenBean bean) {

    }

    /**
     * 手动派包回调
     * @param bean
     */
    @Override
    public void getYbListSuc2(YangbenBean bean) {
        EventBus.getDefault().post(new AddAuditSDEvent());
        showToast("手动派包成功");
        finish();
    }


    /**
     * 获取用户信息回调
     * @param bean
     */
    @Override
    public void getUserListSuc(UserBean bean) {
        if (req.getPageNo() == 1) {
            refreshLayout.setRefreshing(false);
            adapter.setNewData(bean.getResult());
        } else {
            adapter.addData(bean.getResult());
        }
        adapter.openLoadMore(bean.getTotalItems() > adapter.getItemCount());
    }

    /**
     * 手动拍包 回调
     */
    @Override
    public void addLabelSuc() {
        EventBus.getDefault().post(new AddLabelSDEvent());
        showToast("手动派包成功");
        finish();
    }

    @Override
    public void addLabelSuc2() {

    }

}
